#!/bin/env python
#-*- coding:utf-8 -*-

#----------------------------------------------------------------------------
# Name     :      GUI.py
# Purpose  :      Mysql tool for ucweb, and this is the py file of gui.
# Author   :      Albert cheng
# Created  :      2012-10-29
# Copyright:     (c) 2012 by Albertcheng
# Licence  :      wxWindows license
#----------------------------------------------------------------------------
import os
import re
import time
import string
import wx          
import sys
import wx.lib.delayedresult as dr
wx.SetDefaultPyEncoding("utf-8")

from gui_dbconfig import DBConfigDialog
from gui_DataGrid import DataConfigDialog
from gui_grid import GRID_STRING,GRID_NUMBER,GRID_BOOL,GRID_CHOICE,CustTableGrid
from log import Log
from dbo import *
from request_handler import request_mysql,request_sqlite,request_xml

    
class GUITool(wx.Frame):
    def __init__(self, parent, title):
        #=======================================================================
        # 初始化部分参数和变量
        #=======================================================================
        self.Log = Log()
        self.Log.log("program started. initialized variables.")
        self.errflag = False
        self.Title_Msg = title
        self.JobID = 0
        
        self.sqlite_request = request_sqlite(self.Log)
        self.mysql_request = request_mysql(self.Log)
        self.xml_request = request_xml(self.Log)
        
        self.Log.log("tool started. initialized tool gui.")
        #=======================================================================
        # 界面的主画布初始化
        #=======================================================================
        wx.Frame.__init__(self, parent, -1, title, size = (900, 720),
                          style= wx.CAPTION| wx.MINIMIZE_BOX |wx.CLOSE_BOX| wx.NO_FULL_REPAINT_ON_RESIZE)
        self.SetMinSize((300,300))
        
        #=======================================================================
        # 界面状态栏初始化和设置
        #=======================================================================
        self.CreateStatusBar()
        self.SetStatusText(self.Title_Msg)
        #=======================================================================
        # 界面菜单栏处理
        #=======================================================================
        self.menu_prepare()
        #=======================================================================
        # 界面布局处理
        #=======================================================================
        #self.sizer_prepare()

        #=======================================================================
        # 界面和数据库的连接检查 
        #=======================================================================
        self.Log.log("gui render finished, about to try to connect to mysql server.")
        self.run_bg_mysql_thread()
               
        #self.run_bg_get_mysql_data()
        #=======================================================================
        # 所有操作事件的绑定
        #=======================================================================
        #self.__evt_binding()
        
    def run_bg_mysql_thread(self):
        #self.JobManager = []
        self.Mysql_BG_Thread_Flag = True
        def __run(evt):
            #self.JobID += 1
            #self.JobManager.append(self.JobID)
            dr.startWorker(self.refresh_gui, self.refresh_mysql)#, wargs=(), jobID = self.JobID)
        self.bg_thread_timer = wx.Timer(self)
        self.thread_abortEvent = dr.AbortEvent()
        self.thread_abortEvent.clear()
        self.Bind(wx.EVT_TIMER,__run,self.bg_thread_timer)
        self.bg_thread_timer.Start(10000)

    def refresh_gui(self,dr):
        self.Log.log("refresh gui by threadID [%s]" )
        
    def refresh_mysql(self):
        self.Log.log("refresh mysql by threadid [%s]" )
        st = time.time()
        if self.Mysql_BG_Thread_Flag:
            rd = self.mysql_request.refresh("fightgame","t_player","DEAD","player_id")

            data = rd[0]
            for k,v in data["fightgame"].items():
                print "tb is ", k
                for k1,v1 in v.items():
                    print "----",k1," is ----",v1
        self.Log.log("refresh mysql over, by threadid [%s]" )
        
        
        #self.mysql_timer = wx.Timer(self)
        #self.mysql_timer.Start(6000)
        #Evt_Timer_BG_Mysql
    

    def menu_prepare(self):
        # Prepare the menu bar
        menuBar = wx.MenuBar()

        # 1st menu from left
        menu1 = wx.Menu()
        menu1.Append(101, "&配置Mysql连接参数".decode('utf-8'), "配置mysql的链接参数".decode('utf-8'))
        menu1.Append(102, "&关闭".decode('utf-8'), "关闭工具".decode('utf-8'))
        # Add menu to the menu bar
        menuBar.Append(menu1, "&配置".decode('utf-8'))

        # 2nd menu from left
        menu2 = wx.Menu()
        menu2.Append(201, "关于".decode('utf-8'))
        menuBar.Append(menu2, "&关于".decode('utf-8'))

        self.SetMenuBar(menuBar)

    def __update_sqlitedata(self):
        cfg = self.request.getcfg()
        if len(cfg) > 1:
            self.dbcfg = cfg[0]
            self.prefer = cfg[1]
            self.proj_data = self.prefer[0]
            self.projs = self.proj_data.split(';')
            #print self.prefer
            self.proj_id = int(self.prefer[1])
            self.database_id = self.prefer[2]
            self.Proj = self.projs[self.proj_id]
        else:
            wx.MessageBox("Config.DB file is broken or missing, Please repair it.","Fatal Error",wx.OK)
            self.Destroy()
            sys.exit(1)
        
    def __evt_binding(self):
        
        #=======================================================================
        # 菜单栏的事件绑定
        #=======================================================================
        self.Bind(wx.EVT_MENU, self.Evt_MenuEvt101, id=101)
        self.Bind(wx.EVT_MENU, self.Evt_MenuEvt102, id=102)
        self.Bind(wx.EVT_MENU, self.Evt_MenuEvt201, id=201)

        #=======================================================================
        # 搜索按钮的事件绑定
        #=======================================================================
        #self.filter.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN,lambda e: self.filter.SetValue(''))
        #self.filter.Bind(wx.EVT_TEXT_ENTER, self.OnSearch)
        #=======================================================================
        # 界面编辑，保存按钮事件绑定，放在sizer处理中单独进行
        #=======================================================================

        #=======================================================================
        # 关闭界面的事件绑定
        #=======================================================================
        self.Bind(wx.EVT_CLOSE, self.Evt_OnCloseWindow)
        
        
    def Evt_MenuEvt101(self,e):
        def __compare(old_d,new_d):
    
            for n in old_d:
                if int(n[1]) == 1:
                    o_ip = n[2]
                    o_port = n[3]
                    o_user = n[4]
                    o_pass = n[5]
                    o_char = n[6]
                     
            for m in new_d:
                if int(m[1]) == 1:
                    n_ip = m[2]
                    n_port = m[3]
                    n_user = m[4]
                    n_pass = m[5]
                    n_char = m[6]
            
            if o_ip != n_ip:
                return False
            if o_port != n_port:
                return False
            if o_user != n_user:
                return False
            if o_pass != n_pass:
                return False
            if o_char != n_char:
                return False
            return True
        
        dlg = DBConfigDialog()
        dlg.ShowModal()
        self.cfg_new = self.sdbo.showalldata()
        if not __compare(self.cfg,self.cfg_new):
            self.Evt_OnCloseWindow(e)
            frame = GUITool(None, self.Title_Msg)
            frame.Show()
            frame.Center()
        
    def Evt_MenuEvt102(self,e):
        self.Evt_OnCloseWindow(e)
        
    def Evt_MenuEvt201(self,e):
        dlg = wx.MessageDialog(self, "Thank you for using this tool which designed for uc's game testing!\nif you meet any problems when you're using, please contact me with chengjie@ucweb.com",
                               'Ion Hammer albertcheng',
                               wx.OK | wx.ICON_INFORMATION
                               #wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_INFORMATION
                               )
        dlg.ShowModal()
        dlg.Destroy()
          
    def Evt_OnCloseWindow(self, evt):
        try:
            radio_proj_inx = self.projs.index(self.proj)
            db = self.ch_db_c.GetSelection()            
        except:
            radio_proj_inx = 0

        #self.sdbo.dosql(["update prefer set lastprojid='%s', lastdatabaseid='%s';" % (radio_proj_inx,db)])
        
        try:
            self.thread_abortEvent.set()
        except:
            self.Destroy()
        self.Destroy() 
         


    def Evt_OnEditRoleSizer(self,e):        
        
        if self.use_data != {} and self.use_data.has_key("player"):
            if self.filter.GetValue().strip() == "":
                wx.MessageBox("未填写帐号信息，不能编辑数据".decode('utf-8'),"Error",wx.OK)
                return
            self.Update_Flag = False
            for name ,value in self.sizer5_items.items():
                if "line_box_info_vlaue_" in name:
                    value.SetEditable(True)
                    value.SetBackgroundColour("#E0EEEE")
       
    def Evt_OnSaveRoleSizer(self,e):
        if self.use_data != {} and self.use_data.has_key("player"):
            if self.filter.GetValue().strip() == "":
                wx.MessageBox("未填写帐号信息，不能提交数据".decode('utf-8'),"Error",wx.OK)
                return
            
        for name ,value in self.sizer5_items.items():
            if "line_box_info_vlaue_" in name:
                value.SetEditable(False)
                value.SetBackgroundColour("#F2F2F2")

        role_tags = [t for t in self.sizer5_items.keys() if  "line_box_info_vlaue_" in t]
        role_tags.sort()
        
        role_data = {}
        for ntag in range(len(self.sizer5_Tag_Area)):
            role_data[self.sizer5_Tag_Area[ntag]] = self.sizer5_items[role_tags[ntag]].GetValue()
            
        p_db = self.ch_db_c.GetStringSelection().strip()
        
        sql_update_player = self.use_cfg_sql["player"][1] % (p_db,\
                                                                       role_data["agility"],\
                                                                       role_data["energy"],\
                                                                       role_data["exp"],\
                                                                       role_data["level"],\
                                                                       role_data["max_hp"],\
                                                                       role_data["name"],\
                                                                       role_data["power"],\
                                                                       role_data["speed"],\
                                                                       role_data["uc_id"],\
                                                                       role_data["player_id"],\
                                                                       )
        try:
            self.dbh.dosql(sql_update_player)
        except MySQLdb.Error,e:
            self.Log.log(e[1])
            return
        self.Update_Flag = True
         
         
    def showall(self):
        if self.filter.GetValue().strip() == "":
            return
        self.__get_all_tb_data()
        if len(self.use_data) != 0:
            self.__show_playerdata()
            self.__show_vipdata()
            self.__show_prop_data()
            self.__show_weapon_data()
            self.__show_skill_data()
            self.errflag = False
        else:
            if not self.errflag: 
                self.errflag = True
                self.Update_Flag = False
                self.filter.SetValue("")
                wx.MessageBox("未查询到数据，请检查数据库配置".decode('utf-8'),"Error",wx.OK)
            
            
            
    def __get_all_tb_data(self):
        p_db = self.ch_db_c.GetStringSelection().strip()
        idx = self.filter.GetValue().strip()
        if p_db == "" or idx == "":
            return
        self.sqld = self.request_sql.get()
        self.use_cfg_sql = self.sqld[self.proj] 
        
        self.use_data = {}

        querysql = self.use_cfg_sql["player"][0] % (p_db,idx,idx)
        
        try:
            rd = self.dbh.dosql(querysql)
            if rd != ():
                rd = rd[0]
                self.use_data["player"] = rd
                self.player_id = rd[0]
            else:
                self.use_data["player"] = ()
                self.player_id = ""
        except MySQLdb.Error,e:
            self.Log.log(e[1])
            self.use_data["player"] = () 
            return False
                
        for k, v in self.use_cfg_sql.items():
            
            querysql = v[0]
            if k == "player":
                continue
            
            if querysql.strip()  == "":
                continue
            querysql = querysql % (p_db,self.player_id)
            
            try:
                rd = self.dbh.dosql(querysql)
                if rd != (): 
                    self.use_data[k] = rd
                else:
                    self.use_data[k] = ()
            except MySQLdb.Error,e:
                self.Log.log(e[1])
                self.use_data[k] = ()
            
    def __show_playerdata(self):
        if self.use_data["player"] == ():
            show_data = [
                         "",
                         "",
                         "",
                         "",
                         "",
                         "",
                         "",
                         "",
                         "",
                         "",
                         ]
        else:
            try:
                player_data = self.use_data["player"]
            except:
                self.Update_Flag = False
                self.filter.SetValue("")
                wx.MessageBox("未配置好角色表相关sql语句，请检查本地的sql配置文件".decode('utf-8'))
                return
            
            if player_data != (): 
                show_data = [
                                    player_data[16],#uc_id
                                    player_data[0],#player_id,
                                    player_data[13],#name
                                    player_data[10],#level
                                    player_data[4],#exp
                                    player_data[12],#max_hp
                                    player_data[3],#energy
                                    player_data[1],#agility
                                    player_data[14],#power
                                    player_data[15],#speed 
                        ]
            
        role_tags = [t for t in self.sizer5_items.keys() if  "line_box_info_vlaue_" in t]
        role_tags.sort()    
        for ntag in range(len(role_tags)):
            new_v = str(show_data[ntag])
            old_v = self.sizer5_items[role_tags[ntag]].GetValue()
            new_v = new_v.decode('utf-8')
                
            self.sizer5_items[role_tags[ntag]].SetValue(new_v)
            if old_v != "" and old_v != new_v:
                self.sizer5_items[role_tags[ntag]].SetStyle(0, 47, wx.TextAttr("RED", wx.NullColour))
            else:
                self.sizer5_items[role_tags[ntag]].SetStyle(0, 47, wx.TextAttr("#228B22",wx.NullColour))
                
    def __show_vipdata(self):
        
        if self.use_data["player"] == () or self.use_data["misc"] == ():
            vipdata = ["","","",""]
        else:
            player_data = self.use_data["player"]
            misc_data = self.use_data["misc"][0]
            
             
            vip_deadline = player_data[17]
            last_login_time = player_data[7]  
            
            vip_level = misc_data[9]
            vip_exp = misc_data[8]
            
            vipdata = [vip_deadline,vip_level,vip_exp,last_login_time]
            
            
        vip_tags = [t for t in self.sizer6_items.keys() if  "line_box_info_vlaue_" in t]
        vip_tags.sort()
            
        for ntag in range(len(vip_tags)):
            new_v = str(vipdata[ntag])
            old_v = self.sizer6_items[vip_tags[ntag]].GetValue()
            
            self.sizer6_items[vip_tags[ntag]].SetValue(str(vipdata[ntag]).decode('utf-8'))
            
            if old_v != "" and old_v != new_v:
                self.sizer6_items[vip_tags[ntag]].SetStyle(0, 47, wx.TextAttr("RED", wx.NullColour))
            else:
                self.sizer6_items[vip_tags[ntag]].SetStyle(0, 47, wx.TextAttr("#228B22",wx.NullColour))
        
                       
    def __get_name_by_id(self,l,idx,tag):
        
        for m in l:
            if int(m[0]) == int(idx):
                return m[tag]  
    
    def __show_prop_data(self):
        props_data = []
        if self.use_data["prop"] != ():
            self.props_cfg = self.request_sql.getxml("props.xml","<prop id=")
            try:
                props_data = self.use_data["prop"]
            except:
                return
        show_data = []

        for nitem in props_data:
            item_prop_id = int(nitem[3])
            item_cnt = int(nitem[2])
            item_idx = int(nitem[0])
            item_name = self.__get_name_by_id(self.props_cfg,item_prop_id,1)
            show_data.append((item_idx,item_name,item_cnt))
        for nitem in range(len(show_data),99):
            show_data.append(("","",""))
        for nrow in range(len(show_data)):
            for ncol in range(len(show_data[nrow])):
                self.item_g.SetValue(nrow,ncol,str(show_data[nrow][ncol]).decode('utf-8'))
                            
    def __show_weapon_data(self):
        weapons_data = []
        if self.use_data["weapon"] != ():
            self.weapons_cfg = self.request_sql.getxml("weapons.xml","<weapon id=")
            try:
                weapons_data = self.use_data["weapon"]
            except:
                return
        show_data = []
        for nitem in weapons_data:
            item_weapons_id = int(nitem[2])
            item_lvl = int(nitem[3])
            item_idx = int(nitem[0])
            item_name = self.__get_name_by_id(self.weapons_cfg,item_weapons_id,1)
            show_data.append((item_idx,item_name,item_lvl))
        for nitem in range(len(show_data),99):
            show_data.append(("","",""))
        for nrow in range(len(show_data)):
            for ncol in range(len(show_data[nrow])):
                self.weapon_g.SetValue(nrow,ncol,str(show_data[nrow][ncol]).decode('utf-8'))
                    
    def __show_skill_data(self):
        skills_data = []
        if self.use_data["skill"] != ():
            self.skills_cfg = self.request_sql.getxml("skills.xml","<skill id=")
            try:
                skills_data = self.use_data["skill"]
            except:
                return
        show_data = []

        for nitem in skills_data:
            item_skills_id = int(nitem[3])
            item_lvl = int(nitem[2])
            item_idx = int(nitem[0])
            item_name = self.__get_name_by_id(self.skills_cfg,item_skills_id,1)
            show_data.append((item_idx,item_name,item_lvl))
        for n in range(len(show_data),99):
            show_data.append(("","",""))
        for nrow in range(len(show_data)):
            for ncol in range(len(show_data[nrow])):
                self.skill_g.SetValue(nrow,ncol,str(show_data[nrow][ncol]).decode('utf-8'))
                    
    def OnBEVipSizer(self,e):
        if self.filter.GetValue().strip() == "":
            self.Update_Flag = False
            return
        viptime = int(time.time()*1000) + 10000000000
        #ssdz|misc2|update|update
        role_tags = [t for t in self.sizer6_items.keys() if  "line_box_info_vlaue_" in t]
        role_tags.sort()
        
        
        p_db = self.ch_db_c.GetStringSelection().strip()
        vip_data = {}
        for ntag in range(len(self.sizer6_Tag_Area)):
            vip_data[self.sizer6_Tag_Area[ntag]] = self.sizer6_items[role_tags[ntag]].GetValue()
        sql_update_misc = [  self.use_cfg_sql["misc2"][1] % (p_db,\
                                                       viptime,\
                                                        vip_data["last_login_time"],\
                                                        self.player_id)]    
        
        try:
            self.dbh.dosql(sql_update_misc)
        except MySQLdb.Error,e:
            self.Log.log(e[1])
            return
        self.Update_Flag = True 
        self.__show_vipdata()
    
    def OnEditVipSizer(self,e):
        self.Update_Flag = False
        
        #print self.Update_Role_Flag
        for name ,value in self.sizer6_items.items():
            if "line_box_info_vlaue_" in name:
                if "1" in name or "2" in name:
                    value.SetEditable(True)
                    value.SetBackgroundColour("#E0EEEE")
    
    
    
    def OnSaveVipSizer(self,e):
        #print "save vip "
        #print self.Update_Role_Flag
        for name ,value in self.sizer6_items.items():
            if "line_box_info_vlaue_" in name:
                value.SetEditable(False)
                value.SetBackgroundColour("#F2F2F2")
        if self.filter.GetValue().strip() == "":
            self.Update_Flag = False
            return
        
        role_tags = [t for t in self.sizer6_items.keys() if  "line_box_info_vlaue_" in t]
        role_tags.sort()
        
        vip_data = {}
        for ntag in range(len(self.sizer6_Tag_Area)):
            vip_data[self.sizer6_Tag_Area[ntag]] = self.sizer6_items[role_tags[ntag]].GetValue()
            
        p_db = self.ch_db_c.GetStringSelection().strip()
        
        sql_update_misc = [self.use_cfg_sql["misc1"][1] % (p_db,\
                                                        #vip_data["vip_deadline"],\
                                                        vip_data["vip_level"],\
                                                        vip_data["vip_exp"],
                                                        self.player_id),
                                                        #vip_data["last_login_time"])    
        
                        self.use_cfg_sql["misc2"][1] % (p_db,\
                                                        vip_data["vip_deadline"],\
                                                        vip_data["last_login_time"],\
                                                        self.player_id)]    
        #self.Log.log(''.join(sql_update_misc))
        try:
            self.dbh.dosql(sql_update_misc)
        except MySQLdb.Error,e:
            self.Log.log(e[1])
            return
        self.Update_Flag = True                 
                                

                
                
    def sizer_prepare(self):
        self.panel = wx.Panel(self,-1,size = (2000,2000))
        #----------------------------------
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer0 = wx.BoxSizer(wx.HORIZONTAL)
        sizer1 = wx.BoxSizer(wx.HORIZONTAL)
        sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer3 = wx.BoxSizer(wx.HORIZONTAL)
        #----------------------------------
        proj_t = wx.StaticText(self.panel,-1,"当前使用项目:".decode('utf-8'))
        
        def inner_rad(p,projs):
            names = locals()
            for nproj in range(len(projs)):
                name = "radio_%s" % nproj
                if nproj == 0:
                    names[name] = wx.RadioButton( p, -1, projs[nproj], style = wx.RB_GROUP )
                else:
                    names[name] = wx.RadioButton( p, -1, projs[nproj])
                if str(self.proj_id) in name:
                    names[name].SetValue(True)
                else:
                    names[name].SetValue(False)
                    
            rd = {}
            for k,v in names.items():
                if "radio" in k:
                    rd[k] = v
            return rd
        #----------------------------------
        sizer0.Add(proj_t,0,wx.CENTER|wx.ALL,5)
        self.proj_items = inner_rad(self.panel,self.projs)
        for n in range(len(self.proj_items)):
            sizer0.Add(self.proj_items["radio_%s" % n],0,wx.EXPAND,5)
            self.Bind(wx.EVT_RADIOBUTTON, self.OnProjSelect, self.proj_items["radio_%s" % n])
        #----------------------------------
        ch_db_t = wx.StaticText(self.panel,-1,"选择要连接的Database".decode('utf-8'))
        self.ch_db_c = wx.Choice(self.panel,-1,choices=[])
        self.ch_db_c.Bind(wx.EVT_CHOICE,self.OnSelect)    
        sizer0.Add(ch_db_t,0,wx.CENTER|wx.ALL,5)
        sizer0.Add(self.ch_db_c,0,wx.LEFT|wx.ALL,5)
        #----------------------------------
        self.filter_t = wx.StaticText(self.panel,-1,"查询您的UCID或者角色昵称：".decode('utf-8'))
        self.filter = wx.SearchCtrl(self.panel,-1, size=(500,25),style=wx.TE_PROCESS_ENTER)
        self.filter.ShowCancelButton(True)
        #----------------------------------
        sizer2.Add(self.filter_t,0,wx.CENTER|wx.ALL,5)
        sizer2.Add(self.filter,0,wx.LEFT|wx.ALL,5)
        sizer1.Add(wx.StaticLine(self.panel,-1,size=(1000,1)),0,wx.EXPAND,5)
        sizer3.Add(wx.StaticLine(self.panel,-1,size=(1000,1)),0,wx.EXPAND,5)
        self.sizer4 = wx.BoxSizer(wx.VERTICAL)
        
        def __handle_proj_sizer():
            if self.Proj == "ssdz":
                self.sizer5 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="角色基础数据".decode('utf-8')), wx.VERTICAL)
                
                self.sizer5_Info_Area = [
                                    ("UC账号".decode('utf-8'),"PlayerID","角色名".decode('utf-8'),"等级".decode('utf-8'),"经验值".decode('utf-8')),
                                    ("生命值".decode('utf-8'), "活力值".decode('utf-8'), "敏捷属性".decode('utf-8'),"力量属性".decode('utf-8'),"速度属性".decode('utf-8')),
                                    ]
                self.sizer5_Tag_Area = [
                                    "uc_id",
                                    "player_id",
                                    "name",
                                    "level",
                                    "exp",
                                    "max_hp",
                                    "energy",
                                    "agility",
                                    "power",
                                    "speed",
                                    ]
                self.sizer5_items = self.__make_ui_code(self.sizer5_Info_Area,self.sizer5)
                
                
                sizer5_btn = wx.BoxSizer(wx.HORIZONTAL)
                
                self.sizer5_edit = wx.Button(self.panel,-1,"编辑".decode('utf-8'))
                self.sizer5_save = wx.Button(self.panel,-1,"提交".decode('utf-8'))
                
                sizer5_btn.Add(self.sizer5_edit,0,wx.EXPAND,5)
                sizer5_btn.Add(self.sizer5_save,0,wx.EXPAND,5)
                
                self.sizer5.Add(sizer5_btn,0,wx.CENTER|wx.ALIGN_RIGHT,5)
                #===================================================================
                # 
                #===================================================================
                
                
                sizer6 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="角色VIP数据".decode('utf-8')), wx.VERTICAL)
                
    
                self.sizer6_Info_Area = [
                                    ("VIP到期时间".decode('utf-8'),"VIP等级".decode('utf-8'),"VIP经验".decode('utf-8'),"登陆时间".decode('utf-8')),
                                    ]
                self.sizer6_Tag_Area = [
                                    "vip_deadline",
                                    "vip_level",
                                    "vip_exp",
                                    "last_login_time",
                                    ]
                self.sizer6_items = self.__make_ui_code(self.sizer6_Info_Area,sizer6)
                
                
                sizer6_btn = wx.BoxSizer(wx.HORIZONTAL)
                
                self.sizer6_onekey = wx.Button(self.panel,-1,"一键成为VIP".decode('utf-8'))
                self.sizer6_edit = wx.Button(self.panel,-1,"编辑".decode('utf-8'))
                self.sizer6_save = wx.Button(self.panel,-1,"提交".decode('utf-8'))
                
    
                
                
                
                #===================================================================
                # 表格控件处理区域
                #===================================================================
                sizer7 = wx.BoxSizer(wx.HORIZONTAL)
                sizer8 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="角色道具数据".decode('utf-8')), wx.VERTICAL)
                #-------------------------------------------------
                self.item_g = self.__make_grid_code(['Prop表ID'.decode('utf-8'), '道具名'.decode('utf-8'), '道具数量'.decode('utf-8')])
                self.item_g.SetMinSize((300,300))
                #-------------------------------------------------
                sizer9 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="角色武器数据".decode('utf-8')), wx.VERTICAL)
                self.weapon_g = self.__make_grid_code(['Weapon表ID'.decode('utf-8'), '武器名'.decode('utf-8'), '武器等级'.decode('utf-8')])
                self.weapon_g.SetMinSize((300,300))
                #-------------------------------------------------
                sizer10 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="角色技能数据".decode('utf-8')), wx.VERTICAL)
                self.skill_g = self.__make_grid_code(['Skill表ID'.decode('utf-8'), '技能名'.decode('utf-8'), '技能等级'.decode('utf-8')])
                self.skill_g.SetMinSize((300,300))
                #-------------------------------------------------
                item_ot = wx.Button(self.panel,-1,"设置道具数量".decode('utf-8'))
                weapon_ot = wx.Button(self.panel,-1,"设置武器等级".decode('utf-8'))
                skill_ot = wx.Button(self.panel,-1,"设置技能等级".decode('utf-8'))
                #-------------------------------------------------
                self.Bind(wx.EVT_BUTTON,self.OnOt_Prop,item_ot)
                self.Bind(wx.EVT_BUTTON,self.OnOt_Weapon,weapon_ot)            
                self.Bind(wx.EVT_BUTTON,self.OnOt_Skill,skill_ot)
                
                
                sizer12 = wx.BoxSizer(wx.HORIZONTAL)
                sizer13 = wx.BoxSizer(wx.HORIZONTAL)
                
                all_weapon = wx.Button(self.panel,-1,"一键全武器设置等级".decode('utf-8'))
                self.all_weapon_lvl = wx.TextCtrl(self.panel,-1,"1",size=((50,20)))                
                all_skill = wx.Button(self.panel,-1,"一键全技能设置等级".decode('utf-8'))
                self.all_skill_lvl = wx.TextCtrl(self.panel,-1,"1",size=((50,20)))
                
                
                sizer12.Add(all_weapon,0,wx.LEFT|wx.ALL,5)
                sizer12.Add(self.all_weapon_lvl,0,wx.LEFT|wx.ALL,5)       
                
                sizer13.Add(all_skill,0,wx.LEFT|wx.ALL,5)
                sizer13.Add(self.all_skill_lvl,0,wx.LEFT|wx.ALL,5)    
                #===================================================================
                # 功能区域控件处理 
                #===================================================================
                sizer6_btn.Add(self.sizer6_onekey,0,wx.EXPAND,5)
                sizer6_btn.Add(self.sizer6_edit,0,wx.EXPAND,5)
                sizer6_btn.Add(self.sizer6_save,0,wx.EXPAND,5)
                
                sizer6.Add(sizer6_btn,0,wx.CENTER|wx.ALIGN_RIGHT,5)
                
                
                sizer11 = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1, label="神器·偶吧快弄死他！！".decode('utf-8')), wx.VERTICAL)
                #-------------------------------------------------
                GodKeyBox_1 = wx.BoxSizer(wx.HORIZONTAL)
                GodKeyBox_2 = wx.BoxSizer(wx.HORIZONTAL)
                #-------------------------------------------------
                GK_1_1 = wx.Button(self.panel,-1,"启动ADB-Logcat调试日志，需手机连接本机".decode('utf-8'))
                GK_1_2 = wx.Button(self.panel,-1,"black sheep all")
                GK_1_3 = wx.Button(self.panel,-1,"一键神鼠".decode('utf-8'))
                GK_1_4 = wx.Button(self.panel,-1,"一键残鼠".decode('utf-8'))
                GK_1_5 = wx.Button(self.panel,-1,"谁敢比我惨".decode('utf-8'))
                GK_1_6 = wx.Button(self.panel,-1,"天下无敌".decode('utf-8'))
                #-------------------------------------------------
                GK_2_1 = wx.Button(self.panel,-1,"关卡全通".decode('utf-8'))
                GK_2_2 = wx.Button(self.panel,-1,"关卡数据清空".decode('utf-8'))
                GK_2_3 = wx.Button(self.panel,-1,"竞技场第一".decode('utf-8'))
                GK_2_4 = wx.Button(self.panel,-1,"竞技场全数据".decode('utf-8'))
                GK_2_5 = wx.Button(self.panel,-1,"test")
                GK_2_6 = wx.Button(self.panel,-1,"test")
                #-------------------------------------------------
                
                
                
                sizer8.Add(self.item_g,0,wx.EXPAND,5)
                sizer8.Add(item_ot,0,wx.EXPAND,5)
                #-------------------------------------------------
                sizer9.Add(self.weapon_g,0,wx.EXPAND,5)
                sizer9.Add(weapon_ot,0,wx.EXPAND,5)
                sizer9.Add(sizer12,0,wx.EXPAND,5)
                
                
                
                #-------------------------------------------------
                sizer10.Add(self.skill_g,0,wx.EXPAND,5)
                sizer10.Add(skill_ot,0,wx.EXPAND,5)  
                sizer10.Add(sizer13,0,wx.EXPAND,5)

                #-------------------------------------------------
                sizer7.Add(sizer8,0,wx.EXPAND,5)
                sizer7.Add(sizer9,0,wx.EXPAND,5)
                sizer7.Add(sizer10,0,wx.EXPAND,5)
                #-------------------------------------------------
                GodKeyBox_1.Add(GK_1_1,0,wx.EXPAND,5)
                GodKeyBox_1.Add(GK_1_2,0,wx.EXPAND,5)
                GodKeyBox_1.Add(GK_1_3,0,wx.EXPAND,5)
                GodKeyBox_1.Add(GK_1_4,0,wx.EXPAND,5)
                GodKeyBox_1.Add(GK_1_5,0,wx.EXPAND,5)
                GodKeyBox_1.Add(GK_1_6,0,wx.EXPAND,5)
                #-------------------------------------------------
                GodKeyBox_2.Add(GK_2_1,0,wx.EXPAND,5)
                GodKeyBox_2.Add(GK_2_2,0,wx.EXPAND,5)
                GodKeyBox_2.Add(GK_2_3,0,wx.EXPAND,5)
                GodKeyBox_2.Add(GK_2_4,0,wx.EXPAND,5)
                GodKeyBox_2.Add(GK_2_5,0,wx.EXPAND,5)
                GodKeyBox_2.Add(GK_2_6,0,wx.EXPAND,5)
                #-------------------------------------------------
                sizer11.Add(GodKeyBox_1,0,wx.EXPAND,5)
                sizer11.Add(GodKeyBox_2,0,wx.EXPAND,5)
                #-------------------------------------------------
                self.sizer4.Add(self.sizer5,0,wx.EXPAND,5)
                self.sizer4.Add(sizer6,0,wx.EXPAND,5)
                self.sizer4.Add(sizer7,0,wx.EXPAND,5)
                self.sizer4.Add(sizer11,0,wx.EXPAND,5)
                
                
                
                
                #===================================================================
                #  事件绑定
                #===================================================================
                self.Bind(wx.EVT_BUTTON,self.Evt_OnEditRoleSizer,self.sizer5_edit)
                self.Bind(wx.EVT_BUTTON,self.Evt_OnSaveRoleSizer,self.sizer5_save)
                    
                self.Bind(wx.EVT_BUTTON,self.OnBEVipSizer,self.sizer6_onekey)
                self.Bind(wx.EVT_BUTTON,self.OnEditVipSizer,self.sizer6_edit)
                self.Bind(wx.EVT_BUTTON,self.OnSaveVipSizer,self.sizer6_save)
                
                self.Bind(wx.EVT_BUTTON,self.Evt_AllWeaponOT,all_weapon)
                self.Bind(wx.EVT_BUTTON,self.Evt_AllSkillOT,all_skill)
        
                

        
 
        

        


        
        
        __handle_proj_sizer()
        

        
        sizer.Add(sizer0,0,wx.EXPAND,5)
        sizer.Add(sizer1,0,wx.EXPAND,5)
        sizer.Add(sizer2,0,wx.EXPAND,5)
        sizer.Add(sizer3,0,wx.EXPAND,5)
        sizer.Add(self.sizer4,0,wx.EXPAND,5)
        

        
        self.SetSizer(sizer)
        sizer.Fit(self)
    
    def Evt_AllWeaponOT(self,e):
        self._set_value(self.all_weapon_lvl,"weapon", "<weapon id=","weapons.xml","delallweapon")
        
    def Evt_AllSkillOT(self,e):
        self._set_value(self.all_skill_lvl, "skill",  "<skill id=", "skills.xml", "delallskill")
        
        
    def _set_value(self,obj=None,key = None, tag = None, fn = None, delkey = None):
        all_lvl_txt = obj.GetValue()
        
        all_lvl = re.findall(r"\d+",all_lvl_txt)
        
        
        
        if all_lvl == []:
            wx.MessageBox("请输入0-15的整型数值.","Error",wx.OK)
            return
        all_lvl = int(all_lvl[0])
        obj.SetValue(str(all_lvl))
        
        if all_lvl not in range(0,16):
            wx.MessageBox("请输入0-15的整型数值.","Error",wx.OK)
            return
        
        p_db = self.ch_db_c.GetStringSelection().strip()
        idx  = self.filter.GetValue()
        
        if p_db == "" or idx == "":
            wx.MessageBox("未输入查询的帐号.","Error", wx.OK)
            return
         
        getxml = get_sql()
        sqls = []
        sd = getxml.get()[self.proj]
        
        sqls.append(sd[delkey][3] % (p_db,self.player_id))
        
        
        config = getxml.getxml(fn,tag)
        
        up_sqld = sd[key]
        
        self.xmlcfg = {}
        
        for n in config:
            idx = int(n[0])
            
            if not(24 > idx > 18):
                
                if key == "skill":
                    sqls.append(up_sqld[2] % (p_db,all_lvl,n[0],self.player_id))
                elif key == "weapon":
                    sqls.append(up_sqld[2] % (p_db,n[0],all_lvl,self.player_id))
            
        try:
            self.dbh.dosql(sqls)
            wx.MessageBox("Data Applied Successfully.", "SSSSSS", wx.OK)
        except MySQLdb.Error,e:
            self.Log.log(e[1])
            wx.MessageBox("Data Applied Failed.\n"+e[1], "FFFFFFFFF", wx.OK)
        return

        
        

        
    def OnProjSelect(self,e):
        for n in range(len(self.proj_items)):
            if self.proj_items["radio_%s" % n].GetValue():
                self.proj = self.proj_items["radio_%s" % n].GetLabel()
        
        #print dir(self.sizer5)        
        #print self.sizer5.IsShown()
        #self.flag = True
        if self.ssdz_flag:
            self.flag = False
        else:
            self.flag = True
        
        #self.sizer4.Show(self.sizer5,show=self.flag)
        
        
        #self.Refresh()
        
    def OnOt_Prop(self,e):
        idx = self.filter.GetValue().strip()
        if idx == "":
            wx.MessageBox("请先在搜索框填写要监控的ID或昵称".decode('utf-8'),"ERROR",wx.OK)
            return
        
        Tags = ["是否生成".decode('utf-8'),"道具名".decode('utf-8'),"道具数量".decode('utf-8')]
        
        
        chd = ':0,1,10,100,9999'
        proj = "ssdz"
        pc = DataConfigDialog(proj,"道具生成配置界面".decode('utf-8'),"props.xml",\
                              "<prop id=",self.use_data["prop"],\
                              "prop",\
                              self.ch_db_c.GetStringSelection().strip(),\
                              self.player_id,\
                              Tags,\
                              chd)
        pc.ShowModal()
        pc.Destroy()
        
    def OnOt_Weapon(self,e):
        idx = self.filter.GetValue().strip()
        if idx == "":
            wx.MessageBox("请先在搜索框填写要监控的ID或昵称".decode('utf-8'),"ERROR",wx.OK)
            return
        
        Tags = ["是否生成".decode('utf-8'),"武器名".decode('utf-8'),"武器等级".decode('utf-8')]
        
        
        chd = ':0,1,5,10,15'
        proj = "ssdz"
        
        pc = DataConfigDialog(proj,"武器生成配置界面".decode('utf-8'),"weapons.xml",\
                              "<weapon id=",self.use_data["weapon"],\
                              "weapon",\
                              self.ch_db_c.GetStringSelection().strip(),\
                              self.player_id,\
                              Tags,\
                              chd)
        pc.ShowModal()
        pc.Destroy()
         
        
    def OnOt_Skill(self,e):
        idx = self.filter.GetValue().strip()
        if idx == "":
            wx.MessageBox("请先在搜索框填写要监控的ID或昵称".decode('utf-8'),"ERROR",wx.OK)
            return
        
        Tags = ["是否生成".decode('utf-8'),"技能名".decode('utf-8'),"技能等级".decode('utf-8')]
        
        
        chd = ':0,1,5,10'
        proj = "ssdz"
        
        pc = DataConfigDialog(proj,"技能生成配置界面".decode('utf-8'),"skills.xml",\
                              "<skill id=",self.use_data["skill"],\
                              "skill",\
                              self.ch_db_c.GetStringSelection().strip(),\
                              self.player_id,\
                              Tags,\
                              chd)
        pc.ShowModal()
        pc.Destroy()
        
          
    def OnSelect(self,e):
        self.filter.SetValue("")
        self.Update_Flag = False



 
    def __make_grid_code(self,Tags):
        colsize = [(0,80),
                   (1,110),
                   (2,60)]
        dt = [GRID_STRING,GRID_STRING,GRID_STRING]
        return CustTableGrid(self.panel,Tags,dt,colsize,[])      
                
    def __make_ui_code(self,make_data,make_sizer):


        l_names = locals()
        #g_names = globals()
        #value_list = []
        for nline in range(len(make_data)):
            line_box_name = "line_box_%s" % nline
            
            l_names[line_box_name] = wx.BoxSizer(wx.HORIZONTAL)
            
            
            for nitem in  range(len(make_data[nline])):
                
                line_box_info_name = "line_box_info_name_%s_%s" % (nline,nitem)
                line_box_name_value = "line_box_info_vlaue_%s_%s" % (nline,nitem)
                
                l_names[line_box_info_name] = wx.StaticText(self.panel,-1, make_data[nline][nitem])
                l_names[line_box_name_value] = wx.TextCtrl(self.panel,-1,"",style= wx.TE_READONLY|wx.TE_RICH2)#16 is readonly
                l_names[line_box_info_name].SetMinSize((70,20))
                l_names[line_box_name_value].SetMinSize((110,20))
                l_names[line_box_name_value].SetBackgroundColour("#F2F2F2")
                l_names[line_box_name].Add(l_names[line_box_info_name],0,wx.EXPAND|wx.RIGHT,5)
                l_names[line_box_name].Add(l_names[line_box_name_value],0,wx.EXPAND|wx.RIGHT,5)
            
            make_sizer.Add(l_names[line_box_name],0,wx.EXPAND,5)
        
        return l_names
    
        
           
    def OnSearch(self,e):
        for name ,value in self.sizer5_items.items():
            if "line_box_info_vlaue_" in name:
                value.SetEditable(False)
                value.SetBackgroundColour("#F2F2F2")
        for name ,value in self.sizer6_items.items():
            if "line_box_info_vlaue_" in name:
                value.SetEditable(False)
                value.SetBackgroundColour("#F2F2F2")
        self.showall()
        self.errflag = False
        self.Update_Flag = True
        
    def __refresh_dbl(self):
        return self.dbh.getdblist()

 
    
   


